package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.encryptionUtil.FileDecryption;
import com.bootdo.system.dao.FileInfoDao;
import com.bootdo.system.dao.SetDao;
import com.bootdo.system.domain.*;
import com.bootdo.system.service.DeptService;
import com.bootdo.system.service.FileShareService;
import com.bootdo.system.service.UserFileService;
import com.bootdo.system.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件控制管理类
 */
@RequestMapping("/sys/userFile")
@Controller
@EnableAsync
public class UserFileController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 存放路径导航的文件集合
    private List<UserFileDO> folios = null;

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private FileShareService fileShareService;

    @Autowired
    private UserService userService;

    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private SetDao setDao;

    @Autowired
    private DeptService deptService;

    @Autowired
    private BootdoConfig bootdoConfig;

    /***
     * 获取文件列表信息
     * @param params
     * @return
     */
    @GetMapping("/listFile")
    @ResponseBody
    public PageUtils listFile(@RequestParam Map<String, Object> params,UserFileDO userFileDO) {
        //查询列表数据
        params.put("userid",getUserId().toString());
        if(null != userFileDO.getBelong()) {
            params.put("belong",userFileDO.getBelong());
        }else {
            params.put("belong",-1);
        }
        params.put("isreceive","0");
        Query query = new Query(params);
        List<UserFileDO> userFileDOList = userFileService.listFile(query);
        int count = userFileService.countFile(query);
        //Map<String, Object> map = new HashMap<String, Object>();
        //map.put("files", userFileDOList);
        //map.put("catalog", getFolios(userFileDO.getUserid(), userFileDO.getBelong()));
        PageUtils pageUtils = new PageUtils(userFileDOList,getFolios(userFileDO.getUserid(), userFileDO.getBelong()),count);
        return pageUtils;
    }

    private List<UserFileDO> getFolios(Long userid, Integer belong) {
        folios = new ArrayList<UserFileDO>();
        getFolio(belong);
        return folios;
    }

    private void getFolio(int belong) {
        UserFileDO userFileDO = userFileService.getDetail(belong);
        if (userFileDO == null) {
            return;
        }
        if (userFileDO.getBelong() > 0) {
            getFolio(userFileDO.getBelong());
        }
        folios.add(userFileDO);
    }

    /***
     * 创建文件夹
     * @param userFileDO
     * @return
     */
    @PostMapping("/establishFile")
    @Log("创建文件夹")
    @ResponseBody
    public R establishFile(UserFileDO userFileDO) {
        R r = new R();
        //创建人
        userFileDO.setUserid(getUserId());
        userFileDO.setUsername(getUsername());
        r = userFileService.createDir(userFileDO);
        return r;
    }

    /**
     * 文件上传
     * @param file
     * @param userFileDO
     * @return
     */
    @PostMapping("/uploadFile")
    @Log("文件上传")
    @ResponseBody
    public R uploadFile(MultipartFile[] file, UserFileDO userFileDO) {
        R r = new R();
        //创建人
        userFileDO.setUserid(getUserId());
        userFileDO.setUsername(getUsername());
        r = userFileService.uploadFile(file,userFileDO);
        return r;
    }

    /**
     * 文件上传
     * @param fileDO
     * @param theFile
     * @param userFileDO
     * @return
     */
    @PostMapping("/uploadFileFor")
    @Log("文件上传")
    @ResponseBody
    public R uploadFileFor(FileDO fileDO, MultipartFile[] theFile, UserFileDO userFileDO) {
        R r = new R();
        //创建人
        userFileDO.setUserid(getUserId());
        userFileDO.setUsername(getUsername());
        try {
            r = userFileService.uploadFileFor(fileDO,theFile,userFileDO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 文件取消上传
     * @param fileDO
     * @return
     */
    @PostMapping("/cancelUploadFile")
    @Log("文件取消上传")
    @ResponseBody
    public R cancelUploadFile(FileDO fileDO) {
        R r = userFileService.cancelUploadFile(fileDO);
        return r;
    }

    /**
     * 文件同步到另一台服务器
     * @param rootPath
     * @param actualPath
     * @param file
     * @return
     */
    @PostMapping("/synchroFile")
    @ResponseBody
    public R uploadFile(String rootPath, String actualPath, MultipartFile file,String fileId,String uuid,String fileName,String fileType) {
        R r = new R();
        r = userFileService.synchroFile(rootPath,actualPath,file,fileId,uuid,fileName,fileType);
        return r;
    }

    /**
     * 生成文件分享链接
     */
    @PostMapping("/createShareLink")
    @Log("生成文件分享链接")
    @ResponseBody
    public R createShareLink(FileShareDO fileShareDO){
        R r = new R();
        fileShareDO.setCreateBy(getUserId().toString());
        r = fileShareService.createShareLink(fileShareDO);
        return r;
    }

    /**
     * 生成文件分享链接及随机码
     */
    @PostMapping("/getShareLinkAndCode")
    @ResponseBody
    public Map<String,Object> getShareLinkAndCode(FileShareDO fileShareDO){
        //生成分享链接
        String ipAndPort = getServerIpAndPort();
        String usename = getUsername();
        String uuid = UuidUtils.getUUID();
        String action = usename + "&uuid=" + uuid + "&id=" + fileShareDO.getFileId();
        String shareLink = "https://" + ipAndPort + "/sys/userFile/shareLink?action=" + action;
        //参数加密
        String actionMd5 = MD5Utils.encrypt(action);
        String shareLinkMd5 = "https://" + ipAndPort + "/sys/userFile/shareLink?action=" + actionMd5;
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("shareCode",UuidUtils.getRandom());
        map.put("shareLink",shareLink);
        map.put("shareLinkMd5",shareLinkMd5);
        map.put("uuid",uuid);
        return map;
    }

    /**
     * 判断文件是否可以下载
     * @param fileShareDO
     * @return
     */
    @PostMapping("/judeDownloadFile")
    @ResponseBody
    public R judeDownloadFile(FileShareDO fileShareDO) {
        R r = new R();
        r = fileShareService.judeDownloadFile(fileShareDO);
        return r;
    }

    /**
     * 文件下载
     * @param fileShareDO
     * @return
     */
    @GetMapping("/downloadFile")
    @Log("文件下载")
    public void downloadFile(FileShareDO fileShareDO, HttpServletRequest request, HttpServletResponse response) {
        fileShareService.downloadFile(fileShareDO,request,response);
    }

    /**
     * 我上传的文件页面
     * @return
     */
    @GetMapping("/myUploadFileList")
    String myUploadFileList(){
        return "system/userFile/myUploadFileList";
    }

    /**
     * 我收到的文件页面
     * @return
     */
    @GetMapping("/myReceiveFileList")
    String myReceiveFileList(){
        return "system/userFile/myReceiveFileList";
    }

    /**
     * 获取我收到的文件列表信息
     * @param params
     * @return
     */
    @ResponseBody
    @GetMapping("/getMyReceiveFileList")
    public PageUtils getMyReceiveFileList(@RequestParam Map<String, Object> params){
        //查询列表数据
        params.put("userid",getUserId().toString());
        Query query = new Query(params);
        List<UserFileDO> auditList = userFileService.getMyReceiveFileListFor(query);
        int total = userFileService.countFor(query);
        PageUtils pageUtils = new PageUtils(auditList, total);
        return pageUtils;
    }

    /**
     * 发送文件页面
     * @return
     */
    @GetMapping("/toBatchSend")
    String toBatchSend(Model model,Integer [] ids){
        //获取文件信息
        List<UserFileDO> fileList = new ArrayList<UserFileDO>();
        String idsStr = "";
        if(null != ids && ids.length > 0) {
            for(Integer id : ids) {
                UserFileDO userFileDO1 = userFileService.getDetail(id);
                fileList.add(userFileDO1);
                idsStr += id + ",";
            }
        }
        model.addAttribute("fileList", fileList);
        model.addAttribute("idsStr", idsStr);
        return "system/userFile/batchSend";
    }

    /**
     * 选择用户页面
     * @return
     */
    @GetMapping("/toselectUser")
    String toselectUser(String roleId, Model model){
        model.addAttribute("roleId",roleId);
        return "system/userFile/selectUser";
    }

    /**
     * 文件发送
     */
    @PostMapping("/batchSend")
    @Log("文件发送")
    @ResponseBody
    public R batchSend(FileAuditDO fileAuditDO){
        R r = new R();
        fileAuditDO.setSendid(Integer.parseInt(getUserId().toString()));
        r = userFileService.batchSend(fileAuditDO);
        return r;
    }

    /**
     * 判断文件是否可以发送
     */
    @PostMapping("/judeSend")
    @ResponseBody
    public R judeSend(@RequestParam("ids[]") Integer[] ids){
        R r = new R();
        r = userFileService.judeSend(ids);
        return r;
    }

    /**
     * 删除文件及文件夹
     */
    @PostMapping("/deleteFile")
    @Log("文件删除")
    @ResponseBody
    public R deleteFile(@RequestParam("ids[]") Integer[] ids){
        R r = new R();
        r = userFileService.deleteFile(ids);
        return r;
    }

    /**
     * 判断文件是否可以删除（文件夹下有文件不可删除）
     */
    @PostMapping("/judeDeleteFile")
    @ResponseBody
    public R judeDeleteFile(@RequestParam("ids[]") Integer[] ids){
        R r = new R();
        r = userFileService.judeDeleteFile(ids);
        return r;
    }

    /**
     * 用户上传文件统计报表
     * @return
     */
    @GetMapping("/uploadReport")
    @RequiresPermissions("sys:userFile:uploadReport")
    String uploadReport(Model model){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String mon = df.format(m);
        model.addAttribute("startDate", mon);
        model.addAttribute("endDate", df.format(new Date().getTime()));
        return "system/log/uploadReport";
    }

    /**
     * 用户上传文件统计报表列表
     */
    @ResponseBody
    @GetMapping("/report1")
    public PageUtils report1(@RequestParam Map<String, Object> params){
        long userId=getUserId();
        params.put("userid",userId);
        //查询列表数据
        Query query = new Query(params);
        Query query2 = new Query(params);
        List<ReportDo> reportList = userFileService.reportList(query);
        int total = userFileService.reportCount(query2);
        PageUtils pageUtils = new PageUtils(reportList, total);
        return pageUtils;
    }


    @ResponseBody
    @GetMapping("/report1Excel")
    public ResponseEntity<byte[]> report1Excel(String deptId, String startDate, String endDate){
        try {
            Map<String, Object> params= new HashMap<>();
            params.put("deptId",deptId);
            params.put("startDate",startDate);
            params.put("endDate",endDate);
            long userId=getUserId();
            params.put("sendid",userId);
            List<ReportDo> reportList = userFileService.reportList(params);
            return ExcelFormatUtil.buildResponseEntity(report1Excel(reportList,1), "用户上传文件统计报表.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private InputStream report1Excel(List<ReportDo> reportList,int type) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        String[] strs=null;
        // 每一列字段名
        if(type==4){
            strs = new String[] {"时间", "总数"};
        }else if(type==3){
            strs = new String[] {"文件类型", "总数"};
        }else{
            strs = new String[] {"部门名称", "总数"};
        }

        // 字段名所在表格的宽度
        int[] ints = new int[] {5000, 5000};

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);

        if (reportList != null && reportList.size() > 0) {
            for (int i = 0; i < reportList.size(); i++) {
                ReportDo reportDo = reportList.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(reportDo.getTypeName());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(reportDo.getNum()); // 审批人
                cell.setCellStyle(content);
            }
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null){
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }

    @GetMapping("/shareLink")
    public String shareLink(Model model,HttpServletRequest request) {
        //获取加密参数
        String action = request.getParameter("action");
        String ipAndPort = getServerIpAndPort();
        String shareLinkMd5 = "https://" + ipAndPort + "/sys/userFile/shareLink?action=" + action;
        //根据加密链接地址获取分享详情
        FileShareDO fileShareDO = fileShareService.getDetailByshareLinkMd5(shareLinkMd5);
        if(null == fileShareDO) {
            return "system/userFile/noShareLink";
        }
        model.addAttribute("fileId",fileShareDO.getFileId());
        model.addAttribute("uuid",fileShareDO.getUuid());
        return "system/userFile/shareLink";
    }


    /**
     * 文件审批日志报表
     */
    @ResponseBody
    @GetMapping("/reportEchart")
    public R reportEchart(String deptId,String startDate,String endDate){
        Map<String, Object> params=new HashMap<>();
        long userId=getUserId();
        params.put("userid",userId);
        params.put("deptId",deptId);
        params.put("startDate",startDate);
        params.put("endDate",endDate);
        List<ReportDo> reportList = userFileService.reportList(params);
        return R.ok().put("reportList",reportList);
    }



    /**
     * 近10天文件上传统计报表
     * @return
     */
    @GetMapping("/tenReport")
    @RequiresPermissions("sys:userFile:tenReport")
    String tenReport(Model model){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date().getTime()-10*24*60*60*1000);
        model.addAttribute("startDate", time);
        model.addAttribute("endDate", df.format(new Date().getTime()));
        return "system/log/tenReport";
    }


    /**
     * 用户上传文件统计报表列表
     */
    @ResponseBody
    @GetMapping("/report4")
    public PageUtils report4(@RequestParam Map<String, Object> params){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<ReportDo> reportList=new ArrayList<ReportDo>();
        for(int i =9;i>=0;i--){
            String time = df.format(new Date().getTime()-i*24*60*60*1000);
            ReportDo reportDo=userFileService.tenReportByTime(time);
            reportDo.setTypeName(time);
            reportList.add(reportDo);
        }
        /*long userId=getUserId();
        params.put("userid",userId);
        //查询列表数据
        Query query = new Query(params);
        Query query2 = new Query(params);
        List<ReportDo> reportList = userFileService.tenReportList(query);
        int total = userFileService.tenReportCount(query2);*/
        PageUtils pageUtils = new PageUtils(reportList, 10);
        return pageUtils;
    }


    @ResponseBody
    @GetMapping("/report4Excel")
    public ResponseEntity<byte[]> report4Excel(){
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            List<ReportDo> reportList=new ArrayList<ReportDo>();
            for(int i =9;i>=0;i--){
                String time = df.format(new Date().getTime()-i*24*60*60*1000);
                ReportDo reportDo=userFileService.tenReportByTime(time);
                reportDo.setTypeName(time);
                reportList.add(reportDo);
            }
            return ExcelFormatUtil.buildResponseEntity(report1Excel(reportList,4), "近10天文件上传统计报表.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 近10天报表柱形图和饼状图
     */
    @ResponseBody
    @GetMapping("/tenReportEchart")
    public R tenReportEchart(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<ReportDo> reportList=new ArrayList<ReportDo>();
        for(int i =9;i>=0;i--){
            String time = df.format(new Date().getTime()-i*24*60*60*1000);
            ReportDo reportDo=userFileService.tenReportByTime(time);
            reportDo.setTypeName(time);
            reportList.add(reportDo);
        }
        return R.ok().put("reportList",reportList);
    }


    /**
     * 用户发送文件统计报表列表
     */
    @ResponseBody
    @GetMapping("/report3")
    public PageUtils report3(@RequestParam Map<String, Object> params){
        long userId=getUserId();
        params.put("userid",userId);
        //查询列表数据
        Query query = new Query(params);
        Query query2 = new Query(params);
        List<ReportDo> reportList = userFileService.typeList(query);
        int total = userFileService.typeCount(query2);
        PageUtils pageUtils = new PageUtils(reportList, total);
        return pageUtils;
    }


    @ResponseBody
    @GetMapping("/report3Excel")
    public ResponseEntity<byte[]> report3Excel(String filetype, String startDate, String endDate){
        try {
            Map<String, Object> params= new HashMap<>();
            params.put("filetype",filetype);
            params.put("startDate",startDate);
            params.put("endDate",endDate);
            long userId=getUserId();
            params.put("userid",userId);
            List<ReportDo> reportList = userFileService.typeList(params);
            return ExcelFormatUtil.buildResponseEntity(report1Excel(reportList,3), "所有文件类型统计报表.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 所有文件类型统计报表柱状图和饼状图
     */
    @ResponseBody
    @GetMapping("/typeReportEchart")
    public R typeReportEchart(String filetype,String startDate,String endDate){
        Map<String, Object> params=new HashMap<>();
        long userId=getUserId();
        params.put("filetype",filetype);
        params.put("startDate",startDate);
        params.put("endDate",endDate);
        List<ReportDo> typeReportList = userFileService.typeList(params);
        return R.ok().put("reportList",typeReportList);
    }

    /**
     * 获取用户信息
     */
    @ResponseBody
    @PostMapping("/getUserDetail")
    public R getUserDetail(){
        UserDO userDO = userService.get(getUserId());
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://" + bootdoConfig.getLocalDataBaseIp() + ":" + bootdoConfig.getRemoteDataBasePort() + "/" + bootdoConfig.getRemoteDataBaseName());
        dataSource.setUsername(bootdoConfig.getRemoteDataBaseUser());
        dataSource.setPassword(bootdoConfig.getRemoteDataBasePassword());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = "select upload_authority,download_authority from baidujiex.upload_download_authority where user_id =";
        List<UserExDO> list = jdbcTemplate.query(sql + userDO.getUserId(), new RowMapper() {
            @Override
            public Object mapRow(ResultSet resultSet, int i) throws SQLException {
                UserExDO userExDO = new UserExDO();
                userExDO.setDownloadAuthority(resultSet.getString("download_authority"));
                userExDO.setUploadAuthority(resultSet.getString("upload_authority"));
                return userExDO;
            }
        });
        if(CollectionUtils.isNotEmpty(list)) {
            userDO.setUploadAuthority(list.get(0).getUploadAuthority());
            userDO.setDownloadAuthority(list.get(0).getDownloadAuthority());
        }
        return R.ok().put("userDO",userDO);
    }


    /**
     * 文件解密到临时目录中
     * @param fileShareDO
     * @param response
     * @return
     */
    @PostMapping("/decryptedFile")
    @ResponseBody
    public R decryptedFile(FileShareDO fileShareDO, HttpServletResponse response) throws Exception {
        //获取文件地址
        UserFileDO userFileDO = userFileService.getDetail(fileShareDO.getFileId());
        //获取文件保存根目录地址
        SetDO setDO = setDao.get("diskSave");
        String rootPath = setDO.getSetValue();
        //获取文件file_info信息
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("uuid",userFileDO.getFileuuid());
        FileInfoDO fileInfoDO = fileInfoDao.getFileInfoDetail(map);
        String targetFileName = userFileDO.getFilename();
        String targetFileType = userFileDO.getFiletype();

        String filePth = rootPath + File.separator + "ENCRY_" + fileInfoDO.getUuid() + fileInfoDO.getFilename() + "." + fileInfoDO.getFiletype();
        //获取classPath路径
        String tmpDir = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/upload";
        String targetFile = tmpDir + File.separator + userFileDO.getFilename() + "." + fileInfoDO.getFiletype();
        if(StringUtils.equals("doc",fileInfoDO.getFiletype()) || StringUtils.equals("docx",fileInfoDO.getFiletype()) || StringUtils.equals("xls",fileInfoDO.getFiletype()) || StringUtils.equals("xlsx",fileInfoDO.getFiletype())
                || StringUtils.equals("xlsm",fileInfoDO.getFiletype()) || StringUtils.equals("ppt",fileInfoDO.getFiletype()) || StringUtils.equals("pptx",fileInfoDO.getFiletype())) {
            String pdfTargetFile = tmpDir + File.separator + userFileDO.getFilename() + "1.pdf";
            if(!new File(pdfTargetFile).exists()) {
                if (!new File(tmpDir).exists()) {
                    new File(tmpDir).mkdirs();
                }
                FileDecryption.DecryptFiles(new File(filePth),new File(targetFile));
                //如果是word,excel，需要转换为pdf后，再预览
                //获取Doc2HtmlUtil实例
                Doc2HtmlUtil coc2HtmlUtil = Doc2HtmlUtil.getDoc2HtmlUtilInstance();
                File file = new File(targetFile);
                FileInputStream fileInputStream = new FileInputStream(file);
                String pdfFile = coc2HtmlUtil.file2pdfFor(fileInputStream, tmpDir,fileInfoDO.getFilename(),fileInfoDO.getFiletype());
                //获取文件的后缀名
                targetFileType = pdfFile.substring(pdfFile.lastIndexOf("."));
                targetFileType = targetFileType.substring(1,targetFileType.length());
                targetFileName = pdfFile.substring(0,pdfFile.lastIndexOf("."));
            }else {
                targetFileName = fileInfoDO.getFilename() + "1";
                targetFileType = "pdf";
            }
        }else if(StringUtils.equals("txt",fileInfoDO.getFiletype())) {
            //获取txt文件编码格式
            String targetFileFor = tmpDir + File.separator + userFileDO.getFilename() + "1." + fileInfoDO.getFiletype();
            if(!new File(targetFileFor).exists()) {
                if (!new File(tmpDir).exists()) {
                    new File(tmpDir).mkdirs();
                }
                FileDecryption.DecryptFiles(new File(filePth),new File(targetFile));
                String fileCharsetName = getCharset(targetFile);
                if(!StringUtils.equals("UTF-8",fileCharsetName)) {
                    //txt文件保存为utf-8格式
                    InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(targetFile)), fileCharsetName); //ANSI编码
                    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(targetFileFor)), "UTF-8"); //存为UTF-8
                    int len = isr.read();
                    while(-1 != len) {

                        osw.write(len);
                        len = isr.read();
                    }
                    //刷新缓冲区的数据，强制写入目标文件
                    osw.flush();
                    osw.close();
                    isr.close();
                    targetFileName = fileInfoDO.getFilename() + "1";
                }
            }else {
                targetFileName = fileInfoDO.getFilename() + "1";
            }
        }else {
            if(!new File(targetFile).exists()) {
                if (!new File(tmpDir).exists()) {
                    new File(tmpDir).mkdirs();
                }
                FileDecryption.DecryptFiles(new File(filePth),new File(targetFile));
            }
        }
        return R.ok().put("targetFile",targetFileName + "." + targetFileType);
    }

    /**
     * 取得文件编码
     * @param file
     * @return
     */
    public static String getCharset(String file) {
        EncodingDetectUtil s = new EncodingDetectUtil();
        return EncodingDetectUtil.javaname[s.detectEncoding(new File(file))];
    }

    /**
     * 根据文件类型的黑白名单判断当前用户是否可以上传文件
     * 如果上级设置了黑名单，下级设置了白名单，那么应当是以下级为准的。
     * 如果说下级设置的是无，那么就以上级为准。
     * 如果下级也是黑名单，那么应当也是以下级为准。也就是说，
     * 如果下级设置了黑白名单，那么就应该以下级为准，
     * 如果下级没有设置，那就要以上级为准
     */
    @PostMapping("/judeUpload")
    @ResponseBody
    public R judeUpload(){
        //获取用户所在的部门
        long deptId = getUser().getDeptId();
        DeptDO deptDO = deptService.get(deptId);
        R r = new R();
        if(null != deptDO) {
            if(!StringUtils.equals("1",deptDO.getNameListOn()) && deptDO.getParentId() != 0) {
                //递归获取上级
                r = getShow(deptDO.getParentId());
            }else if(!StringUtils.equals("1",deptDO.getNameListType()) && !StringUtils.equals("2",deptDO.getNameListType()) && deptDO.getParentId() != 0){
                //递归获取上级
                r = getShow(deptDO.getParentId());
            }else {
                r.put("deptDO",deptDO);
            }
        }
        return r;
    }

    private R getShow(long parentId) {
        R r = new R();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("parentId",parentId);
        DeptDO deptDO = deptService.getDeptDetail(map);
        if(null != deptDO) {
            if(!StringUtils.equals("1",deptDO.getNameListOn()) && deptDO.getParentId() != 0) {
                //递归获取上级
                r = getShow(deptDO.getParentId());
            }else if(!StringUtils.equals("1",deptDO.getNameListType()) && !StringUtils.equals("2",deptDO.getNameListType())  && deptDO.getParentId() != 0) {
                //递归获取上级
                r = getShow(deptDO.getParentId());
            }else {
                r.put("deptDO",deptDO);
            }
        }
        return r;
    }

}
